package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;

public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.校验参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取登录用户id
        ApUser apUser = ApThreadLocal.getApUser();
        //表示未登录
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if (apUser.getId() == 0) {
            return ResponseResult.okResult(405, "游客身份禁止，需进行登录");
        }

        Boolean isfollow = false, iscollection = false, isunlike = false, islike = false;

        //是否点赞了该文章
        String likes_key = "USER_LIKES_" + dto.getArticleId();
        Boolean likesFlag = redisTemplate.opsForHash().hasKey(likes_key, apUser.getId() + "");
        if (likesFlag) {
            islike = true;
        }

        //是否不喜欢该文章
        String unlikes_key = "USER_UNLIKES_" + dto.getArticleId();
        Boolean unlikesFlag = redisTemplate.opsForHash().hasKey(unlikes_key, apUser.getId() + "");
        if (unlikesFlag) {
            isunlike = true;
        }

        //是否关注该用户
        String follow_key="USER_FOLLOW_"+apUser.getId();
        Boolean followFlag = redisTemplate.opsForHash().hasKey(follow_key, dto.getAuthorId() + "");
        if(followFlag){
            isfollow=true;
        }

        //查看是否收藏了该文章
        String collection_key="USER_COLLECTION_"+dto.getArticleId();
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collection_key, apUser.getId() + "");
        if(collectionFlag){
            iscollection=true;
        }

        //返回数据
        Map map =new HashMap();
        map.put("isfollow",isfollow);
        map.put("iscollection",iscollection);
        map.put("isunlike",isunlike);
        map.put("islike",islike);

        return ResponseResult.okResult(map);
    }
}
